package com.sunwayworld.baseline.framework.utils;

import com.sunwayworld.framework.context.ApplicationContextHelper;
import com.sunwayworld.framework.exception.FtpException;
import com.sunwayworld.framework.io.file.FilePathDTO;
import com.sunwayworld.framework.utils.FtpUtils;
import com.sunwayworld.framework.utils.NumberUtils;
import com.sunwayworld.module.item.file.bean.CoreFileBean;
import com.sunwayworld.module.item.file.service.CoreFileService;
import com.sunwayworld.module.item.file.utils.CoreFileUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.core.env.Environment;

import java.io.File;
import java.io.IOException;

public class FTPUtil {

    private static final Logger logger = LogManager.getLogger(FTPUtil.class);

    public static boolean connect(String addr, int port, String username, String password) {
        FTPClient ftp = new FTPClient();
        try {
            ftp.connect(addr, port);
            boolean loginSuccess = ftp.login(username, password);
            if (!loginSuccess) {
                return false;
            } else {
                return true;
            }
        } catch (IOException var3) {
            logger.error("getFtpClient:{}", var3);
            return false;
        }finally{
            close(ftp);
        }
    }

    public static void disconnect(FTPClient ftp) {
        try {
            ftp.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static String FTP_CHARSET = "GBK";

    public static FTPClient getFtpClient() {
        FTPClient ftpClient = new FTPClient();
        try {
            Environment env = ApplicationContextHelper.getEnvironment();
            ftpClient.connect(env.getProperty("sunway.config.file-server.ftp.url"), NumberUtils.parseInt(env.getProperty("sunway.config.file-server.ftp.port")));
            boolean loginSuccess = ftpClient.login(env.getProperty("sunway.config.file-server.ftp.username"), env.getProperty("sunway.config.file-server.ftp.password"));
            if (!loginSuccess) {
                throw new FtpException("GIKAM.EXCEPTION.FTP.CONNECTION");
            } else {
                ftpClient.setFileType(2);
                if (FTPReply.isPositiveCompletion(ftpClient.sendCommand("OPTS UTF8", "ON"))) {
                    FTP_CHARSET = "UTF-8";
                }
                ftpClient.setControlEncoding(FTP_CHARSET);
                ftpClient.enterLocalPassiveMode();// 设置被动模式
                return ftpClient;
            }
        } catch (IOException var3) {
            logger.error("getFtpClient:{}", var3);
            throw new FtpException("GIKAM.EXCEPTION.FTP.CONNECTION");
        }
    }

    public static void close(FTPClient ftpClient) {
        if (null != ftpClient) {
            try {
                ftpClient.disconnect();
            } catch (IOException var2) {
                if (logger.isDebugEnabled()) {
                    logger.error("Unexpected exception on closing FTP Connection", var2);
                }
            }
        }
    }

    /**
     * 获取file,从ftp下载
     *
     * @param coreFileBean
     * @param coreFileService
     * @return
     */
    public static File getFileByCoreFileBean(CoreFileBean coreFileBean, CoreFileService coreFileService) {
        Environment env = ApplicationContextHelper.getEnvironment();
        String mode = env.getProperty("sunway.config.file-server.mode");
        if ("ftp".equals(mode)){
            FilePathDTO filePathDTO = CoreFileUtils.toFilePath(coreFileBean);
            FTPClient FtpClient = getFtpClient();
            FtpUtils.download(FtpClient, filePathDTO);
        }

        File file = CoreFileUtils.getLocalPath(coreFileBean).toFile();
        return file;
    }
}
